package com.mchsdk.paysdk.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.mchsdk.paysdk.bean.ChannelAndGameInfo;
import com.mchsdk.paysdk.bean.LoginModel;
import com.mchsdk.paysdk.bean.VerifyCode;
import com.mchsdk.paysdk.callback.PlatformLoginCallback;
import com.mchsdk.paysdk.callback.PlatformRegisterCallback;
import com.mchsdk.paysdk.callback.RefreshVerifyCode;
import com.mchsdk.paysdk.common.Constant;
import com.mchsdk.paysdk.dialog.PlatformLoginDialog;
import com.mchsdk.paysdk.dialog.PlatformQuickRegisterDialog;
import com.mchsdk.paysdk.dialog.PlatformRegisterDialog;
import com.mchsdk.paysdk.entity.UserLogin;
import com.mchsdk.paysdk.entity.UserRegister;
import com.mchsdk.paysdk.http.Post;
import com.mchsdk.paysdk.http.checknum.CheckRequest;
import com.mchsdk.paysdk.http.process.LoginProcess;
import com.mchsdk.paysdk.http.process.RegisterPhoneProcess;
import com.mchsdk.paysdk.http.process.RegisterProcess;
import com.mchsdk.paysdk.http.process.ThirdLoginTypeProcess;
import com.mchsdk.paysdk.http.process.VerificationCodeProcess;
import com.mchsdk.paysdk.utils.MCHInflaterUtils;
import com.mchsdk.paysdk.utils.MCLog;
import com.mchsdk.paysdk.utils.PreSharedManager;
import com.mchsdk.paysdk.utils.TextUtils;
import com.mchsdk.paysdk.utils.ToastUtil;
import com.mchsdk.paysdk.view.util.TimeFactory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class LoginActivity {

    private static final String TAG = "LoginActivity";
    private Context context;
    private PlatformLoginDialog loginDialog;
    private PlatformQuickRegisterDialog quickRegisterDialog;
    private PlatformRegisterDialog registerDialog;
    /**
     * 是否快速登录
     */
    private boolean isQuickLogin;

    /**
     * 是否快速登录
     */
    private boolean isSavePassword;

    ProgressDialog dialog;
    Handler handler;


    /**
     * 判断是否为账号登陆或者手机号登陆
     */
    public static boolean isAccount = false;

    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.LOGIN_SUCCESS:// 登陆成功
                    isAccount = true;
                    UserLogin loginSuccess = (UserLogin) msg.obj;
                    handlerLoginResult(loginSuccess);


                    break;
                case Constant.LOGIN_FAIL:// 登陆失败
                    String loginErrorMsg = (String) msg.obj;
                    if (TextUtils.isEmpty(loginErrorMsg)) {
                        loginErrorMsg = "登陆失败";
                    }
                    LoginModel.instance().loginFail();
                    ToastUtil.show(context, loginErrorMsg);
                    break;
                case Constant.USER_WXLOGIN_FAIL://微信第三方登录成功请求SDK服务器
                    //使用普通的登录失败
                    break;
                case Constant.REGISTER_SUCCESS:// 注册成功
                    UserRegister registerSuccess = (UserRegister) msg.obj;
                    registerSuccess(registerSuccess);
                    break;
                case Constant.REGISTER_FAIL:// 注册失败
                    String regErrorMsg = (String) msg.obj;
                    if (TextUtils.isEmpty(regErrorMsg)) {
                        regErrorMsg = "注册失败";
                    }
                    ToastUtil.show(context, regErrorMsg);
                    break;
                case Constant.VERIFYCODE_REQUEST_SUCCESS:// 请求获得手机验证码成功
                    VerifyCode verifyCode = (VerifyCode) msg.obj;
                    getPhoneCodeSuccess(verifyCode);
                    break;
                case Constant.VERIFYCODE_REQUEST_FAIL:// 请求获得手机验证码失败
                    String res = (String) msg.obj;
                    ToastUtil.show(context, res);
                    // 获取验证码失败，更新按钮可点击
                    if (null != registerDialog) {
                        registerDialog.reSendValidateCode();
                    }
                    break;
            }
        }
    };

    /**
     * 构造方法
     *
     * @param context 上下文对象
     */
    public LoginActivity(Context context) {
        this.context = context;
    }


    /**
     * 调用此方法显示登录对话框
     */
    public void showLoginDialog() {

        if (ChannelAndGameInfo.getInstance().haveReadGameInfo()) {
            String account = PreSharedManager.getString(Constant.CUSTOMER, context);
            String pwd = PreSharedManager.getString(Constant.PASSWORD, context);
            String isSavePwd = PreSharedManager.getString(Constant.SAVEPWD, context);
            if (!"1".equals(isSavePwd)) {
                pwd = "";
            }
            isQuickLogin = false;
            isSavePassword = true;
            loginDialog = new PlatformLoginDialog.Builder().setAccount(account)
                    .setPassword(pwd)
                    .setLoginCallback(mLoginCallback)
                    .setForgmentPwdClick(forgetPasswordClick)
                    .setRegisterClick(showRegisterClick)
                    .setThirdLoginClick(thirdLoginClick)
                    .setQuickRegisterClick(visitorsLogin)
                    .setDialogKeyListener(backKeyListener)
                    .show(context, ((Activity) context).getFragmentManager());

            thirdLoginType();

        } else {
            Toast.makeText(context, "获取渠道信息异常", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取后台第三方登录的方式
     */
    private void thirdLoginType() {
        new ThirdLoginTypeProcess().post(logintypeHandle);
    }

    private Handler logintypeHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.THIRD_LOGIN_TYPE_SUCCESS:
                    splitThirdLoginType((String) msg.obj);
                    break;
                case Constant.THIRD_LOGIN_TYPE_FAIL:
                    MCLog.w(TAG, "" + msg.obj);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * @param loginTypeStr "qq|wx|wb|bd"
     */
    private void splitThirdLoginType(String loginTypeStr) {
        boolean isWB = loginTypeStr.contains("wb");
        boolean isQQ = loginTypeStr.contains("qq");
        boolean isWX = loginTypeStr.contains("wx");
        boolean isBD = loginTypeStr.contains("bd");
        if (null != loginDialog) {
            loginDialog.setThirdLoginButtonShow(isWB, isQQ, isWX, isBD);
        }

    }

    /**
     * 显示注册
     */
    private OnClickListener showRegisterClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("点击注册按钮");
            isQuickLogin = true;
            registerDialog = new PlatformRegisterDialog.Builder()
                    .setBackdClick(registerToLoginClick)
                    .setDialogKeyListener(backKeyListener)
                    .setRegisterCallback(registerCallback)
                    .setQuickRegisterClick(showQuickRegisterClick)
                    .setOnFocusChangeListener(onFocusChangeListener)
                    .show(context, ((Activity) context).getFragmentManager());
        }
    };

    /**
     * 显示登陆
     */
    private OnClickListener registerToLoginClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            showLoginDialog();
        }
    };

    /**
     * 注册
     */
    private PlatformRegisterCallback registerCallback = new PlatformRegisterCallback() {

        @Override
        public void platformRegister(String userName, String password, String repassword,
                                     String msg, String res) {
            if (checkRegister(userName, password, msg)) {
                startPhoneUserRegist(userName, password, msg, res);
            }
        }

        @Override
        public void getPhoneValidateMessage(
                final View btnGetPhoneValidateMessage, String userName,
                RefreshVerifyCode refreshCode) {
            if (checkRegister_getPhoneValidateMessage(userName)) {
                VerificationCodeProcess verifyCodeProcess = new VerificationCodeProcess();
                verifyCodeProcess.setPhone(userName);
                // verifyCodeProcess.get(myHandler);
                verifyCodeProcess.post(myHandler);
            } else {
                btnGetPhoneValidateMessage.setEnabled(true);
                btnGetPhoneValidateMessage
                        .setBackgroundResource(MCHInflaterUtils.getIdByName(
                                context, "drawable", "mc_login_reg_phone_num"));
            }
        }
    };

    private OnClickListener visitorsLogin = new OnClickListener() {
        @Override
        public void onClick(View v) {
            isQuickLogin = true;
            isSavePassword = true;
//			startUserRegist(LoginUtils.random() + "", LoginUtils.random() + "");
//            if (FlagControl.isLogin) {
//                PersonalCenterModel.getInstance().offLine(context);
//            }
            LoginModel.instance().startVisitorsLogin();
        }
    };

    /**
     * 显示一键登录
     */
    private OnClickListener showQuickRegisterClick = new OnClickListener() {

        @Override
        public void onClick(View v) {

            isQuickLogin = true;
            isSavePassword = true;
            quickRegisterDialog = new PlatformQuickRegisterDialog.Builder()
                    .setBackdClick(quickregisterToLoginClick)
                    .setDialogKeyListener(backKeyListener)
                    .setQuickRegisterCallback(quickregisterCallback)
                    .setRegisterClick(showRegisterClick)
                    .setOnFocusChangeListener(onFocusAccount)
                    .show(context, ((Activity) context).getFragmentManager());
        }
    };

    /**
     * 第三方登录监听
     */
    View.OnClickListener thirdLoginClick = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String tag = (String) v.getTag();
            dialog = new ProgressDialog(context);
            dialog.setMessage("正在加载,请稍等");
            dialog.show();
            LoginModel.instance().requestThirdLoginParams(tag, context, dialog);
        }
    };

    /**
     * 手机号码失去焦点
     */
    OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            EditText phone = (EditText) v;
            String phonenum = phone.getText().toString().trim();
            boolean isPhone = checkRegister_getPhoneValidateMessage(phonenum);
            if (TextUtils.isEmpty(phonenum)) {
                ToastUtil.show(context, "请输入手机号");
                return;
            }
            if (isPhone) {
                CheckRequest checkRequest = new CheckRequest();
                checkRequest.post = new Post();
                checkRequest.context = context;
                checkRequest.postIsExit(phonenum);
            } else {
                ToastUtil.show(context, "请输入正确的手机号码");
            }
        }
    };

    /**
     * 账号号码失去焦点
     */
    OnFocusChangeListener onFocusAccount = new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            EditText account = (EditText) v;
            String accountnum = account.getText().toString().trim();
            String reg = Constant.REGULAR_ACCOUNT;
            Pattern pattern = Pattern.compile(reg);
            Matcher matcher_acc = pattern.matcher(accountnum);
            boolean b_acc = matcher_acc.matches();
            if (b_acc) {
                CheckRequest checkRequest = new CheckRequest();
                checkRequest.post = new Post();
                checkRequest.context = context;
                checkRequest.postIsExit(accountnum);
            } else {
                ToastUtil.show(context, "请输入6-15位数字或英文字母");
            }
        }
    };
    /**
     * 显示登录
     */
    OnClickListener quickregisterToLoginClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            showLoginDialog();
        }
    };

    /**
     * 快速注册,一键登录
     */
    PlatformRegisterCallback quickregisterCallback = new PlatformRegisterCallback() {

        @Override
        public void platformRegister(String userName, String password, String repassword,
                                     String message, String res) {


            if (TextUtils.isEmpty(userName)) {
                ToastUtil.show(context, "请输入账号");
                return;
            }
            if (userName.trim().length() < 6) {
                ToastUtil.show(context, "账号格式不正确");
                return;
            }
            if (TextUtils.isEmpty(password)) {
                ToastUtil.show(context, "请输入密码");
                return;
            }
            if (!isRegularAcc(password)) {
                ToastUtil.show(context, "密码格式不正确");
                return;
            }
            if (TextUtils.isEmpty(repassword)) {
                ToastUtil.show(context, "请输入确认密码");
                return;
            }
            if (!repassword.equals(password)) {
                ToastUtil.show(context, "两次输入密码不一致");
                return;
            }
//            if (!isRegularAcc(repassword)) {
//                ToastUtil.show(context, "确认密码格式不正确");
//                return;
//            }
//            String reg = Constant.REGULAR_ACCOUNT;
//            Pattern pattern = Pattern.compile(reg);
//            Matcher matcher_acc = pattern.matcher(userName);
//            Matcher matcher_pwd = pattern.matcher(password);
//            Matcher matcher_repwd = pattern.matcher(repassword);
//            boolean b_acc = matcher_acc.matches();
//            boolean b_pwd = matcher_pwd.matches();
//            boolean b_repwd = matcher_repwd.matches();
//            if (!b_acc || !b_pwd || !b_repwd) {
//                ToastUtil.show(context, "请输入6-15位数字或英文字母");
//                return;
//            }
//            if (!repassword.equals(password)) {
//                ToastUtil.show(context, "两次输入密码不一致");
//                return;
//            }

            startUserRegist(userName, password);

        }

        @Override
        public void getPhoneValidateMessage(View v, String userName,
                                            RefreshVerifyCode refreshCode) {

        }
    };


    private boolean isRegularAcc(String account) {
        String reg = Constant.REGULAR_ACCOUNT;
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher_acc = pattern.matcher(account);
        boolean b_acc = matcher_acc.matches();
        if (!b_acc) {
            return false;
        }
        return true;
    }

    /**
     * 忘记密码
     */
    OnClickListener forgetPasswordClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(context, MCForgetPasswordActivity.class);
            context.startActivity(intent);
        }
    };

    /**
     * 登录
     */
    PlatformLoginCallback mLoginCallback = new PlatformLoginCallback() {

        @Override
        public void platformLogin(String userName, String password,
                                  boolean isSavePwd) {
            if (checkLogin(userName, password)) {
                isSavePassword = isSavePwd;
                startUserLogin(userName, password);
            }
        }
    };

    /**
     * 返回按钮监听
     */
    OnKeyListener backKeyListener = new OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            exitThisActivity();
            return false;
        }
    };

    /**
     * 退出当前页面
     */
    private void exitThisActivity() {
        LoginModel.instance().loginFail();
        TransparencyActivity.instance.closeActivity();
    }

    /**
     * 用户信息检查，获取手机验证码
     *
     * @param userName
     * @return
     */
    protected boolean checkRegister_getPhoneValidateMessage(String userName) {
        String phoneNumber = Constant.REGULAR_PHONENUMBER;
        if (TextUtils.isEmpty(userName)) {
            ToastUtil.show(context, "手机号不能为空");
            return false;
        }
        if (!userName.matches(phoneNumber)) {
            ToastUtil.show(context, "请输入正确的手机号码");
            return false;
        }
        return true;
    }

    /**
     * 登录用户信息检查
     */
    public Boolean checkLogin(String str_account, String str_password) {
        if (TextUtils.isEmpty(str_account)) {
            ToastUtil.show(context, "用户名不能为空");
            return false;
        }
        int length = str_account.trim().length();
        if (length < 6) {
            ToastUtil.show(context, "账号格式不正确");
            return false;
        }
        if (TextUtils.isEmpty(str_password)) {
            ToastUtil.show(context, "密码不能为空");
            return false;
        }
        if (!isRegularAcc(str_password)) {
            ToastUtil.show(context, "密码格式不正确");
            return false;
        }
        return true;
    }

    /**
     * 注册用户信息检查
     */
    public Boolean checkRegister(String str_account, String str_password,
                                 String str_message) {
        if (TextUtils.isEmpty(str_account)) {
            ToastUtil.show(context, "请输入手机号");
            return false;
        }
        String reg_acc = Constant.REGULAR_PHONENUMBER;
        Pattern pattern_acc = Pattern.compile(reg_acc);
        Matcher matcher_acc = pattern_acc.matcher(str_account);
        boolean b_acc = matcher_acc.matches();
        if (!b_acc) {
            ToastUtil.show(context, "手机号格式不正确");
            return false;
        }
        if (TextUtils.isEmpty(str_password)) {
            ToastUtil.show(context, "请输入密码");
            return false;
        }
        String reg_pwd = Constant.REGULAR_ACCOUNT;
        Pattern pattern_pwd = Pattern.compile(reg_pwd);
        Matcher matcher_pwd = pattern_pwd.matcher(str_password);
        boolean b_pwd = matcher_pwd.matches();
        if (!b_pwd) {
            ToastUtil.show(context, "密码格式不正确");
            return false;
        }
        if (TextUtils.isEmpty(str_message)) {
            ToastUtil.show(context, "验证码不能为空");
            return false;
        }
        return true;
    }

    /**
     * 注册请求
     *
     * @param string_name     用户名
     * @param string_password 密码
     */
    private void startUserRegist(final String string_name,
                                 final String string_password) {

        RegisterProcess registerProcess = new RegisterProcess();
        registerProcess.setAccount(string_name);
        registerProcess.setPassword(string_password);
        registerProcess.post(myHandler);
    }

    /**
     * 注册请求
     *
     * @param string_name     用户名
     * @param string_password 密码
     */
    private void startPhoneUserRegist(final String string_name,
                                      final String string_password, final String string_message,
                                      String res) {
        RegisterPhoneProcess registerProcess = new RegisterPhoneProcess();
        registerProcess.setAccount(string_name);
        registerProcess.setPassword(string_password);
        registerProcess.setCode(string_message);
        registerProcess.post(myHandler);
    }

    /**
     * 成功请求手机验证码
     */
    private void getPhoneCodeSuccess(VerifyCode verifyCode) {
        MCLog.e(TAG,
                "#getPhoneCodeSuccess  verifyCode= " + verifyCode.toString());
        ToastUtil.show(context, "验证码发送成功　请注意查收");
        TimeFactory.creator(1).Start();
    }

    /**
     * 注册成功
     *
     * @param registerSuccess 返回值
     */
    private void registerSuccess(UserRegister registerSuccess) {
        MCLog.e(TAG,
                "fun#registerSuccess result= " + registerSuccess.getStatus());
        if (registerSuccess.getStatus().equals("1")) {
            if (!TextUtils.isEmpty(registerSuccess.getUserName())
                    && !TextUtils.isEmpty(registerSuccess.getPassword())) {
                LoginModel.instance().saveRegisterInfoToPre(true, registerSuccess.getUserName(),
                        registerSuccess.getPassword());
                if (isQuickLogin) {
                    startUserLogin(registerSuccess.getUserName(),
                            registerSuccess.getPassword());
                } else {
                    TimeFactory.creator(1).calcel();
                    ToastUtil.show(context, "注册成功");
                }
            } else {
                ToastUtil.show(context, "登录失败");
            }
        } else {
            String res = registerSuccess.getRegisterResult();
            if (!TextUtils.isEmpty(res)) {
                if ("null".equals(res)) {
                    ToastUtil.show(context, "账号已被注册");
                    return;
                }
                ToastUtil.show(context, registerSuccess.getRegisterResult());
            }
        }
    }

    /**
     * 开始登陆
     *
     * @param string_name     用户名
     * @param string_password 密码
     */
    private void startUserLogin(String string_name, String string_password) {
        MCLog.w(TAG, "string_name = " + string_name);
        LoginProcess loginprocess = new LoginProcess();
        loginprocess.setAccount(string_name);
        loginprocess.setPassword(string_password);
        loginprocess.post(myHandler);
    }

    /**
     * 登陆成功
     */
    protected void handlerLoginResult(UserLogin loginSuccess) {
        MCLog.w(TAG, "Account = " + loginSuccess.getUserName());
        if ("1".equals(loginSuccess.getLoginStatus())) {
            LoginModel.instance().loginSuccess(true, isSavePassword, loginSuccess);
            dismisDialog();
//			noticeResult(77);
        } else {
            LoginModel.instance().loginFail();

        }
    }

    /**
     * 调用此方法关闭登录对话框
     */
    public void dismisDialog() {
        try {
            if (dialog != null) {
                dialog.dismiss();
            }
            if (loginDialog != null) {
                loginDialog.dismiss();
            }
            if (quickRegisterDialog != null) {
                quickRegisterDialog.dismiss();
            }
            if (registerDialog != null) {
                registerDialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
            MCLog.e(TAG, "dismisDialog error:" + e.toString());
        }
    }

    /**
     * @param type handler的send方法
     */
    private void noticeResult(int type) {
        Message msg = new Message();
        msg.what = type;
        if (null != handler) {
            handler.sendMessage(msg);
        }
    }
}
